<template>
  <div class="admin-referral-management">
    <div class="header">
      <h1>관리자 추천코드 관리</h1>
      <p class="description">관리자 전용 추천코드를 생성하고 관리할 수 있습니다.</p>
    </div>

    <div class="content">
      <!-- 추천코드가 없는 경우 -->
      <div v-if="!referralProfile" class="no-referral-card">
        <div class="card">
          <div class="card-header">
            <h2>추천코드 생성</h2>
          </div>
          <div class="card-body">
            <p>아직 관리자 추천코드가 생성되지 않았습니다.</p>
            <p>추천코드를 생성하면 사용자들이 이 코드를 사용하여 회원가입할 수 있습니다.</p>
            <button
              @click="generateReferralCode"
              :disabled="loading"
              class="btn btn-primary"
            >
              <span v-if="loading">생성 중...</span>
              <span v-else>추천코드 생성</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 추천코드가 있는 경우 -->
      <div v-else class="referral-card">
        <div class="card">
          <div class="card-header">
            <h2>관리자 추천코드</h2>
            <div class="status-badge" :class="{ active: referralProfile.isActive, inactive: !referralProfile.isActive }">
              {{ referralProfile.isActive ? '활성' : '비활성' }}
            </div>
          </div>
          <div class="card-body">
            <div class="referral-info">
              <div class="info-item">
                <label>추천코드:</label>
                <div class="code-display">
                  <span class="code">{{ referralProfile.referralCode }}</span>
                  <button @click="copyToClipboard(referralProfile.referralCode)" class="btn btn-copy">
                    복사
                  </button>
                </div>
              </div>
              <div class="info-item">
                <label>생성일:</label>
                <span>{{ formatDate(referralProfile.createdAt) }}</span>
              </div>
              <div class="info-item">
                <label>마지막 수정:</label>
                <span>{{ formatDate(referralProfile.updatedAt) }}</span>
              </div>
            </div>

            <div class="actions">
              <button
                @click="toggleStatus"
                :disabled="loading"
                class="btn"
                :class="referralProfile.isActive ? 'btn-warning' : 'btn-success'"
              >
                <span v-if="loading">처리 중...</span>
                <span v-else>{{ referralProfile.isActive ? '비활성화' : '활성화' }}</span>
              </button>
              <button
                @click="regenerateCode"
                :disabled="loading"
                class="btn btn-secondary"
              >
                <span v-if="loading">생성 중...</span>
                <span v-else>새 코드 생성</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 추천 통계 -->
        <div class="stats-card">
          <div class="card">
            <div class="card-header">
              <h3>추천 통계</h3>
            </div>
            <div class="card-body">
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-value">{{ referralStats.totalReferrals || 0 }}</div>
                  <div class="stat-label">총 추천 회원</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ referralStats.activeReferrals || 0 }}</div>
                  <div class="stat-label">활성 회원</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">{{ referralStats.thisMonthReferrals || 0 }}</div>
                  <div class="stat-label">이번 달 신규</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 토스트 메시지 -->
    <div v-if="toast.show" class="toast" :class="toast.type">
      {{ toast.message }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import request from '@/utils/request'

interface ReferralProfile {
  id: string
  referralCode: string
  profileType: string
  isActive: boolean
  createdAt: string
  updatedAt: string
}

interface ReferralStats {
  totalReferrals: number
  activeReferrals: number
  thisMonthReferrals: number
}

const referralProfile = ref<ReferralProfile | null>(null)
const referralStats = ref<ReferralStats>({
  totalReferrals: 0,
  activeReferrals: 0,
  thisMonthReferrals: 0
})
const loading = ref(false)
const toast = ref({
  show: false,
  message: '',
  type: 'success'
})

// 페이지 로드 시 추천코드 정보 가져오기
onMounted(async () => {
  await loadReferralProfile()
  if (referralProfile.value) {
    await loadReferralStats()
  }
})

// 추천코드 정보 로드
const loadReferralProfile = async () => {
  try {
    const response = await request.get('/api/admin/admin-referral')
    if (response.data.profile) {
      referralProfile.value = response.data.profile
    }
  } catch (error: any) {
    if (error.response?.status !== 404) {
      showToast('추천코드 정보를 가져오는데 실패했습니다.', 'error')
    }
  }
}

// 추천 통계 로드
const loadReferralStats = async () => {
  try {
    const response = await request.get('/api/admin/admin-referral/stats')
    referralStats.value = response.data
  } catch (error) {
    console.error('추천 통계 로드 실패:', error)
    showToast('추천 통계를 가져오는데 실패했습니다.', 'error')
  }
}

// 추천코드 생성
const generateReferralCode = async () => {
  loading.value = true
  try {
    const response = await request.post('/api/admin/admin-referral')
    referralProfile.value = response.data.profile
    showToast('추천코드가 성공적으로 생성되었습니다.', 'success')
    await loadReferralStats()
  } catch (error: any) {
    showToast(error.response?.data?.error || '추천코드 생성에 실패했습니다.', 'error')
  } finally {
    loading.value = false
  }
}

// 상태 토글
const toggleStatus = async () => {
  if (!referralProfile.value) return

  loading.value = true
  try {
    const newStatus = !referralProfile.value.isActive
    const response = await request.put('/api/admin/admin-referral', {
      isActive: newStatus
    })
    referralProfile.value = response.data.profile
    showToast(`추천코드가 ${newStatus ? '활성화' : '비활성화'}되었습니다.`, 'success')
  } catch (error: any) {
    showToast(error.response?.data?.error || '상태 변경에 실패했습니다.', 'error')
  } finally {
    loading.value = false
  }
}

// 새 코드 생성
const regenerateCode = async () => {
  if (!confirm('새로운 추천코드를 생성하시겠습니까? 기존 코드는 더 이상 사용할 수 없습니다.')) {
    return
  }

  loading.value = true
  try {
    const response = await request.post('/api/admin/admin-referral/regenerate')
    referralProfile.value = response.data.profile
    showToast('새로운 추천코드가 생성되었습니다.', 'success')
  } catch (error: any) {
    showToast(error.response?.data?.error || '코드 재생성에 실패했습니다.', 'error')
  } finally {
    loading.value = false
  }
}

// 클립보드에 복사
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    showToast('추천코드가 클립보드에 복사되었습니다.', 'success')
  } catch (error) {
    showToast('복사에 실패했습니다.', 'error')
  }
}

// 날짜 포맷팅
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('ko-KR')
}

// 토스트 메시지 표시
const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  toast.value = { show: true, message, type }
  setTimeout(() => {
    toast.value.show = false
  }, 3000)
}
</script>

<style scoped>
.admin-referral-management {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 32px;
}

.header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.description {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;
}

.card-header {
  padding: 24px 24px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2,
.card-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.card-body {
  padding: 24px;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
}

.status-badge.active {
  background: #e8f5e8;
  color: #2d7d32;
}

.status-badge.inactive {
  background: #ffeaa7;
  color: #d68910;
}

.no-referral-card .card-body {
  text-align: center;
  padding: 48px 24px;
}

.no-referral-card p {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.5;
}

.referral-info {
  margin-bottom: 32px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

.info-item label {
  font-weight: 500;
  color: #333;
  min-width: 100px;
}

.code-display {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 18px;
  font-weight: 600;
  color: #2563eb;
  background: #f0f9ff;
  padding: 8px 16px;
  border-radius: 8px;
  border: 2px solid #bfdbfe;
}

.actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #2563eb;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #1d4ed8;
}

.btn-success {
  background: #16a34a;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #15803d;
}

.btn-warning {
  background: #d97706;
  color: white;
}

.btn-warning:hover:not(:disabled) {
  background: #b45309;
}

.btn-secondary {
  background: #6b7280;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #4b5563;
}

.btn-copy {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
  padding: 6px 12px;
  font-size: 12px;
}

.btn-copy:hover:not(:disabled) {
  background: #e5e7eb;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
}

.stat-item {
  text-align: center;
  padding: 24px;
  background: #f8fafc;
  border-radius: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2563eb;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.toast {
  position: fixed;
  top: 24px;
  right: 24px;
  padding: 16px 24px;
  border-radius: 8px;
  color: white;
  font-weight: 500;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
}

.toast.success {
  background: #16a34a;
}

.toast.error {
  background: #dc2626;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .admin-referral-management {
    padding: 16px;
  }

  .header h1 {
    font-size: 24px;
  }

  .card-body {
    padding: 16px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .code-display {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    width: 100%;
  }

  .code {
    word-break: break-all;
    width: 100%;
  }

  .actions {
    flex-direction: column;
  }

  .btn {
    width: 100%;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
